﻿#pragma once
#include <memory>
#include <QAbstractItemModel>
#include <QModelIndex>
#include <QVariant>
#include <QQmlEngine>
#include <treedata.h>

Q_DECLARE_METATYPE(CusTreeNode)
QML_DECLARE_TYPE(CusTreeNode)

class TreeModel : public QAbstractItemModel
{
    Q_OBJECT
public:
    explicit TreeModel(QObject *parent = nullptr);
    ~TreeModel();

    enum nodeRoles {
        NODE_NAME = Qt::UserRole + 1,
        NODE_PTR = Qt::UserRole + 2,
    };

    Q_ENUM(nodeRoles)
    Q_INVOKABLE QVariant data(const QModelIndex &index, int role) const override;
    bool setData(const QModelIndex &index, const QVariant &value, \
                        int role = Qt::EditRole) override;
    Qt::ItemFlags flags(const QModelIndex &index) const override;
    QVariant headerData(int section, Qt::Orientation orientation,
                        int role = Qt::DisplayRole) const override;
    QModelIndex index(int row, int column,
                      const QModelIndex &parent = QModelIndex()) const override;
    QModelIndex parent(const QModelIndex &index) const override;
    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    int columnCount(const QModelIndex &parent = QModelIndex()) const override;
    QHash<int, QByteArray> roleNames() const override;
    ////////////////业务相关///////////////////////////
    // 释放所有数据
    void freeModelData();
    // 加载数据
    Q_INVOKABLE void loadData();

    static void declareQML();

    // 开始重新加载model
    void beginResetTreeModel();
    // 结束重新加载
    void endResetTreeModel();
    // 刷新指定节点
    Q_INVOKABLE void updateModelData();
    // 删除刷新
    void startDeletelModelData(const QModelIndex &parent, int first, int last);
    void endDeleteModelData();
    // 插入刷新
    void startInsertModelData(const QModelIndex &parent, int first, int last);
    void endInsertModelData();

private:
    LPCusTreeNode createNodeByFile(const QString& fileName, const QString& TestData);
    void resetModelData(LPCusTreeNode rootItem);

    LPCusTreeNode m_emptyItem;                                  // (-1,-1)的虚假节点
    LPCusTreeNode m_rootItem;                                  // (0, 0)的根节点
    QList<LPCusTreeNode> m_listNodes;                           // 所有节点
};

